﻿using System.Linq;
using System.Reflection;
using Autodesk.AutoCAD.Internal.Reactors;
using Autodesk.AutoCAD.Ribbon;

namespace AutoCADDotNetLibrary
{
    /// <summary>
    /// Ribbon初始化（要求：公有无参方法，如果是实例，则要有无参构造函数）
    /// </summary>
    public class RibbonInitializeAttribute : InitializeAttribute
    {
        /// <summary>
        /// Ribbon初始化，当workspace改变时，重新运行这个函数
        /// </summary>
        /// <param name="workspaceNames">工作空间集合，为空时为所有工作空间（当workspace改变时，重新运行这个函数）</param>
        public RibbonInitializeAttribute(params string[] workspaceNames)
        {
            _workspaceNames = workspaceNames;
        }

        private string[] _workspaceNames;

        /// <summary>
        /// 调用方法
        /// </summary>
        /// <param name="method">需要执行Ribbon初始化的函数</param>
        internal override void InvokeMethod(MethodInfo method)
        {
            //初始加载时
            RibbonServices.CreateRibbonPaletteSet();
            base.InvokeMethod(method);

            //工作空间切换时，执行
            CuiEventManager.Instance().WorkspaceRestore += (sender, e) =>
            {
                if (_workspaceNames.Length == 0)
                {
                    base.InvokeMethod(method);
                }
                else
                {
                    if (_workspaceNames.Any(x => x == e.Name))
                    {
                        base.InvokeMethod(method);
                    }
                }
            };
        }
    }
}
